package com.emenu;

import com.emenu.application.StaticObject;
import com.emenu.bean.User;
import com.emenu.common.Common;
import com.emenu.common.JsonUntil;

import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;

public class FunctionLoginActive extends ActivityGroup {
	private EditText view_funuserID;
	private EditText view_funuserPW;
	private Button button_funsubmit;
	private Button button_funcancel;
	private Intent intent;

	StaticObject SO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.funlogin);

		findViewsById();
		setListener();

		SO = (StaticObject) getApplication();
		view_funuserID.setText(SO.getStaticUser());
	}

	/** 视图 样式 */
	private void findViewsById() {

		view_funuserID = (EditText) findViewById(R.id.funuser_id);
		view_funuserPW = (EditText) findViewById(R.id.funuser_pw);
		button_funsubmit = (Button) findViewById(R.id.funsubmit);
		button_funcancel = (Button) findViewById(R.id.funcancel);
	}

	/** 设置监听器 */
	private void setListener() {
		button_funsubmit.setOnClickListener(submitListener);
		button_funcancel.setOnClickListener(cancelListener);
	}

	/** 提交监听器事件 */
	private OnClickListener submitListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String userCode = String.valueOf(view_funuserID.getText()).trim();
			String userPW = String.valueOf(view_funuserPW.getText()).trim();
			boolean isCheck = false;

			if ("".equals(userCode) || "".equals(userPW)) {
				Common.alertFinish(FunctionLoginActive.this, "账号或密码不能为空");

			} else {

				for (User ub : SO.getUserList()) {
					// 用户输入的密码经过MD5转换后和数据库下载来的密码是否一致，使用JsonUntil.isPassword

					if (ub.getCode().equals(userCode)
							&& JsonUntil.isPassword(userPW, ub.getPassword())) {
						SO.setStaticUserName(ub.getName());
						isCheck = true;
						break;
					}
				}

				if (isCheck) {
					SO.setStaticUser(userCode);
					SO.setStaticUserPW(userPW);

					View view = getLocalActivityManager().startActivity(
							"ReferenceName",
							new Intent(FunctionLoginActive.this,
									FunMainActivity.class)
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
							.getDecorView();
					FunctionLoginActive.this.setContentView(view);

				} else {
					Common.alertFinish(FunctionLoginActive.this, "密码错误");
				}
			}
		}
	};

	/** 取消监听器事件 */
	private OnClickListener cancelListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			view_funuserID.setText("");
			view_funuserPW.setText("");
		}
	};

}
